package com.sndscl.rpc.zk;

import com.alibaba.fastjson.JSONArray;
import com.sndscl.rpc.common.constant.SndSclConstant;
import com.sndscl.rpc.common.util.ZookeeperClient;
import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.*;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/16 16:58
 **/
public class ZkUtil {

    private static  ZookeeperClient zookeeperClient = null;

    public synchronized static void connection(String zkUrl){
        if(zookeeperClient == null){
            zookeeperClient = new ZookeeperClient();
            try {
                zookeeperClient.connection(zkUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, HashSet<String>> addWatcher(){
        try {
            //添加服务节点监听
            List<String> childrens =zookeeperClient.weatherDir(SndSclConstant.ROOT_PATH,new NodeChangeWatcher(zookeeperClient));
            System.out.println(childrens);
            Map<String, HashSet<String>> serverListtMap = new HashMap<>();
            for(int i = 0; i < childrens.size(); i++){
                String serverNode = childrens.get(i);
                byte[] data = new byte[0];
                try {
                    data = zookeeperClient.getData(SndSclConstant.ROOT_PATH+"/"+serverNode);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String nodeData  = new String(data);
                System.out.println(serverNode + " "+ nodeData);
                JSONArray jsonArray = (JSONArray) JSONArray.parse(nodeData);
                List interfaceList =  Arrays.asList(jsonArray.toArray());
                HashSet<String> interfaceSet = new HashSet<>();
                interfaceSet.addAll(interfaceList);
                serverListtMap.put(serverNode,interfaceSet);
            }
            return serverListtMap;
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
